<?php

namespace App\Http\Controllers;

use App\User;
use GatewayClient\Gateway;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use const http\Client\Curl\AUTH_ANY;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
        // 设置GatewayWorker服务的Register服务ip和端口
        Gateway::$registerAddress = '127.0.0.1:1238';
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('home');
    }

    public function init(Request $request)
    {
        //绑定用户
        $this->bind($request);
        //修改自己的状态为在线
        DB::table('users')->where('id', Auth::id())->update(['status' => 'online']);
        return json_encode(['code' => 0, 'msg' => '']);
    }

    /**
     * 绑定client_id 与 user id
     */
    private function bind($request)
    {
        $id = Auth::id();
        $client_id = $request->client_id;
        Gateway::bindUid($client_id, $id);

        $groups = DB::table('group_member')->where('user_id', $id)->select('group_id')->get();
        foreach ($groups as $group) {
            Gateway::joinGroup($client_id, $group->group_id);
        }
    }

    public function me()
    {
        $user = Auth::user();
        $data = [];
        $data['mine']['username'] = $user['name'];
        $data['mine']['status'] = $user['status'];
        $data['mine']['id'] = $user['id'];
        $data['mine']['sign'] = $user['sign'];
        $data['mine']['avatar'] = $user['avatar'];


        $data['friend'] = DB::table('friend_group')->where('user_id', $user['id'])->get()->each(function (&$item) {
            $list = DB::table('friend')->where('friend_group_id', $item->id)->first();
            $item->list = DB::table('users')
                ->where('id', $list->friend_id)
                ->select('name as username', 'id', 'avatar', 'sign', 'status')
                ->get()->toArray();
        });
        $obj = DB::table('group_member')->where('user_id', Auth::id())->get();
        foreach ($obj as $value) {
            $data['group'][] = DB::table('group')->where('id', $value->group_id)->first();
        }

        return json_encode(['code' => 0, 'msg' => '', 'data' => $data]);
    }

    //群成员
    function groupMembers(Request $request)
    {
        $list = DB::table('group_member as m')
            ->Join('users as u', 'm.user_id', '=', 'u.id')
            ->where('m.group_id', $request->id)
            ->select('u.name as username', 'u.id', 'u.avatar', 'u.sign')
            ->get();
        return json_encode(['code' => 0, 'msg' => '', 'data' => ['list' => $list]]);
    }

    //聊天记录
    function chat_log(Request $request)
    {
        if ($request->type == 'friend') {
            $data = DB::table('chat_record as cr')
                ->join('users as u', 'u.id', '=', 'cr.user_id')
                ->where([['cr.user_id', '=', $request->id], ['cr.friend_id', '=', Auth::id()]])
                ->orWhere([['cr.user_id', '=', Auth::id()], ['cr.friend_id', '=', $request->id]])
                ->limit('10')->offset(($request->page - 1) * 10)
                ->orderBy('time', 'desc')
                ->select('u.name as username', 'u.id', 'u.avatar', 'time as timestamp', 'cr.content')->get();
//                var_dump($data);
            $count = DB::table('chat_record as cr')
                ->join('users as u', 'u.id', '=', 'cr.user_id')
                ->where([['cr.user_id', '=', $request->id], ['cr.friend_id', '=', Auth::id()]])
                ->orWhere([['cr.user_id', '=', Auth::id()], ['cr.friend_id', '=', $request->id]])
                ->count();
        } else if ($request->type == 'group') {
            $data = DB::table('chat_record as cr')
                ->join('users as u', 'u.id', '=', 'cr.user_id')
                ->where('cr.group_id', $request->id)
                ->limit('10')->offset(($request->page - 1) * 10)
                ->orderBy('time', 'desc')
                ->select('u.name as username', 'u.id', 'u.avatar', 'time as timestamp', 'cr.content')
                ->get();
            $count = DB::table('chat_record as cr')
                ->where('cr.group_id', $request->id)->count();
        }
        $count = ceil($count / 10);
        foreach ($data as $k => &$v) {
            $v->timestamp = $v->timestamp * 1000;
        }
        $list['data'] = $data;
        $list['last_page'] = $count;
//        var_dump($list);
        return json_encode(['code' => 0, 'msg' => '', 'data' => $list]);
    }

    //聊天
    function say(Request $request)
    {
        switch ($request['type']) {
            case 'chatMessage_one':
                $data = [
                    'username' => $request['data']['mine']['username'] //消息来源用户名
                    , 'avatar' => $request['data']['mine']['avatar'] //消息来源用户头像
                    , 'id' => $request['data']['mine']['id'] //消息的来源ID（如果是私聊，则是用户id，如果是群聊，则是群组id）
                    , 'type' => $request['data']['to']['type'] //聊天窗口来源类型，从发送消息传递的to里面获取
                    , 'content' => $request['data']['mine']['content']//消息内容
                    , 'cid' => 0 //消息id，可不传。除非你要对消息进行一些操作（如撤回）
                    , 'mine' => false //是否我发送的消息，如果为true，则会显示在右方
                    , 'fromid' => $request['data']['mine']['id'] //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
                    , 'timestamp' => time() * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
                ];
                //判断私聊用户是否在线
                if (Gateway::isUidOnline($request['data']['to']['id']) == 1) {
                    Gateway::sendToUid($request['data']['to']['id'], json_encode(['type' => 'chatMessage_one', 'data' => $data]));
                } else {//用户离线
                    DB::table('offline_message')->insert([
                        'user_id' => $request['data']['to']['id'],
                        'data' => json_encode($data),
                    ]);
                }
                //保存消息到数据库
                $record_data = [
                    'user_id' => $request['data']['mine']['id'],
                    'friend_id' => $request['data']['to']['id'],
                    'group_id' => 0,
                    'content' => $request['data']['mine']['content'],
                    'time' => time()
                ];
                DB::table('chat_record')->insert($record_data);
                return json_encode(['code' => 0, 'msg' => '']);
                break;
            case 'chatMessage_group':
                $data = [
                    'username' => $request['data']['mine']['username'] //消息来源用户名
                    , 'avatar' => $request['data']['mine']['avatar'] //消息来源用户头像
                    , 'id' => $request['data']['to']['id'] //消息的来源ID（如果是私聊，则是用户id，如果是群聊，则是群组id）
                    , 'type' => $request['data']['to']['type'] //聊天窗口来源类型，从发送消息传递的to里面获取
                    , 'content' => $request['data']['mine']['content']//消息内容
                    , 'cid' => 0 //消息id，可不传。除非你要对消息进行一些操作（如撤回）
                    , 'mine' => false //是否我发送的消息，如果为true，则会显示在右方
                    , 'fromid' => $request['data']['mine']['id'] //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
                    , 'timestamp' => time() * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
                ];
                $group_members = DB::table('group_member')
                    ->where('group_id', $request['data']['to']['id'])
                    ->where('user_id', '<>', Auth::id())
                    ->select('user_id')
                    ->get();
                foreach ($group_members as $group_member) {
                    if (Gateway::isUidOnline($group_member->user_id) == 1) {
                        Gateway::sendToUid($group_member->user_id, json_encode(['type' => 'chatMessage_group', 'data' => $data]));
                    } else {//用户离线
                        DB::table('offline_message')->insert([
                            'user_id' => $group_member->user_id,
                            'data' => json_encode($data),
                        ]);
                    }
                }
                //保存消息到数据库
                $record = [
                    'user_id' => $request['data']['mine']['id'],
                    'friend_id' => 0,
                    'group_id' => $request['data']['to']['id'],
                    'content' => $request['data']['mine']['content'],
                    'time' => time()
                ];
                DB::table('chat_record')->insert($record);
                return json_encode(['code' => 0, 'msg' => '']);
                break;
        }
    }

    //修改签名
    function update_sign(Request $request)
    {
        if ($request->isMethod('post')) {
            $obj = DB::table('users')->where('id', Auth::id())->update(['sign' => $request['sign']]);
            if ($obj == 1) {
                return json_encode(['code' => 200, 'msg' => '修改成功']);
            } else {
                return json_encode(['code' => 0, 'msg' => '修改失败']);
            }
        }
    }

    //离线消息
    function offline_message()
    {
        $rec = DB::table('offline_message')->where('user_id', Auth::id())->where('status', 0)->get();
        if (!empty($rec)) {
            foreach ($rec as $value) {
                $data1 = json_decode($value->data, true);
                //发送离线消息
                if ($data1['type'] == 'friend') {
                    Gateway::sendToUid(Auth::id(), json_encode(['type' => 'chatMessage_one', 'data' => $data1]));
                } else if ($data1['type'] == 'group') {
                    Gateway::sendToUid(Auth::id(), json_encode(['type' => 'chatMessage_group', 'data' => $data1]));
                }
            }
            foreach ($rec as $value) {
                //修改离线消息状态
                DB::table('offline_message')->where('id', $value->id)->update(['status' => 1]);
            }
        }
        return json_encode(['code' => 0, 'msg' => '']);
    }

    //修改自己的在线状态
    function change_stauts(Request $request)
    {
        DB::table('users')->where('id', Auth::id())->update(['status' => $request->status]);
        return json_encode(['code' => 0, 'msg' => '']);
    }
}
